/*
 * @lc app=leetcode.cn id=106 lang=cpp
 *
 * [106] 从中序与后序遍历序列构造二叉树
 */
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <unordered_map>
#include <cmath>

using namespace std;
// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    unordered_map<int, int> index;
public:
    TreeNode* helpBuild(vector<int>& inorder, vector<int>& postorder,int inLeft,int inRight,int postLeft,int postRight) {
        if(postRight < postLeft) {
            return nullptr;
        }
        int postRoot = postRight;
        int inorderRoot = index[postorder[postRoot]];
        int leftLength = inorderRoot - inLeft;
        TreeNode* root = new TreeNode(postorder[postRoot]);
        root->left = helpBuild(inorder,postorder,inLeft,inorderRoot-1,postLeft,postLeft + leftLength-1);
        root->right = helpBuild(inorder,postorder,inorderRoot+1,inRight,postLeft+leftLength,postRight-1);
        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int n = inorder.size();
        for(int i = 0;i < n;i++) {
            index[inorder[i]] = i;
        }
        return helpBuild(inorder,postorder,0,n-1,0,n-1);
    }
};
// @lc code=end

